import datetime
import sys
import gspread
import time
import os
import myOut as msg
from googleAccount import *

class myLogger:
    gc = 0
    connected = False

    def __init__(self, sheetTag, tempFile):
        # Login with your Google account
        self.start = time.time()
        self.email = email
        self.password = password
        self.sheetTag = sheetTag 
        self.connectFailCnt = 0
        self.worksheet = 0
        self.filename = tempFile
        self.unRecorded = os.path.isfile(tempFile) # keep track if there is anything in the logfile
        print datetime.datetime.now() , " initialized logger to %s" % self.sheetTag
        
        
    # myLogger takes an open sheet and appends a row
    # with the date & vals (vals should be tab delimited for each col)
    def log(self, vals):
        try:
            if (not myLogger.connected):
                myLogger.gc = gspread.login(self.email, self.password)
                myLogger.connected = True
            if (self.worksheet == 0):
                self.worksheet = myLogger.gc.open(self.sheetTag).sheet1
            if (self.unRecorded):
                try:
                    fid = open(self.filename,'r')
                    ls = fid.readlines()
                    fid.close()
                    for lin in ls[:]: # loop over a copy of the list as we are modifying the original list
                        values = lin.split('\t') # sould be datetime / values / recorded status
                        self.worksheet.append_row(values)
                        ls.remove(lin) # remove from list if successfully written
                    os.remove(self.filename)
                    self.unRecorded = False # keep track if there is anything in the logfile
                    msg.myOut( " recovered all data from %s" % self.filename)
                except:
                    fid = open(self.filename,'w')
                    fid.write(ls) # write any lines that could not be uploaded
                    fid.close()
                   
            values = [datetime.datetime.now(), vals]
            self.worksheet.append_row(values)
        except:
            e = sys.exc_info()[0]
            print "Error: %s" % e
            print "%s" % self.sheetTag
            self.connectFailCnt += 1
            myLogger.connected = False
            self.worksheet = 0
            msg.myOut(  " Unable to reconnect %d in %d hours" % (self.connectFailCnt , \
                     (time.time() - self.start) / 3600.0) )
            self.logToFile(vals)
    
    # try to keep anything locally that we can't get to google, put it up later
    def logToFile(self, vals):
        try:
            self.unRecorded = True
            fid = open(self.filename,'a')
            fid.write( str(datetime.datetime.now()) + '\t'+ str(vals) + '\n')
            fid.close()
            msg.myOut(  " wrote to %s" % self.filename )
        except:
            msg.myOut(  " Failed to open the emergency log file")
            
            
def main():
    # apparently open by URL isn't working, not sure why
    tName = 'automationR'
    filename = './temp1_var'

    exampleLogger = myLogger(tName,filename)
    exampleLogger.log('test')

if __name__ == "__main__":
    main()
